//
//  WCFileReference.m
//  alias
//
//  Created by William Towe on 3/26/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCFileReference.h"
#import "NDAlias.h"


#define kWCFRAliasKey @"alias"
#define kWCFRIsDirectoryKey @"isDirectory"

@implementation WCFileReference
- (void)dealloc {
	[_alias release];
	[super dealloc];
}

- (id)initWithCoder:(NSCoder *)coder {
	if (!(self = [super init]))
		return nil;
	
	_alias = [[coder decodeObjectForKey:kWCFRAliasKey] retain];
	_WCFileReferenceFlags.isDirectory = [coder decodeBoolForKey:kWCFRIsDirectoryKey];
	
	return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
	[coder encodeObject:[self alias] forKey:kWCFRAliasKey];
	[coder encodeBool:[self isDirectory] forKey:kWCFRIsDirectoryKey];
}

- (id)copyWithZone:(NSZone *)zone {
	WCFileReference *copy = [[[self class] alloc] init];
	
	copy->_alias = [_alias retain];
	copy->_WCFileReferenceFlags.isDirectory = _WCFileReferenceFlags.isDirectory;
	
	return copy;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
	WCFileReference *copy = [[[self class] alloc] initWithFilePath:[self path]];
	
	return copy;
}

@synthesize alias=_alias;

@dynamic path;
- (NSString *)path {
	NSString *p = [_alias path];
	if (p == nil)
		return [_alias lastKnownPath];
	return p;
}
- (void)setPath:(NSString *)value {
	[_alias setPath:value];
}

@dynamic name;
- (NSString *)name {
	NSString *n = [_alias displayName];
	if (n == nil)
		return [_alias lastKnownName];
	return n;
}
- (void)setName:(NSString *)value {
	if ([value isEqualToString:[_alias displayName]])
		return;
	
	NSString *newPath = [[[self path] stringByDeletingLastPathComponent] stringByAppendingPathComponent:value];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) {
		NSString *message = [NSString stringWithFormat:NSLocalizedString(@"\"%@\" Already Exists",@"message text for file already exists alert"), [newPath lastPathComponent]];
		NSString *format = [NSString stringWithFormat:NSLocalizedString(@"A file named \"%@\" already exists at \"%@\". Would you like to add a numbered suffix to the end of the new file name and then rename the existing file using the new file name?", @"format text for file already exists alert"), [newPath lastPathComponent], newPath];
		NSAlert *alert = [NSAlert alertWithMessageText:message defaultButton:NSLocalizedString(@"Add Suffix",@"Add Suffix") alternateButton:NSLocalizedString(@"Cancel",@"Cancel") otherButton:nil informativeTextWithFormat:format];
		
		[alert setIcon:[self icon]];
		
		[alert beginSheetModalForWindow:[NSApp keyWindow] modalDelegate:self didEndSelector:@selector(_alertDidEnd:code:info:) contextInfo:(void *)[value retain]];
		
		return;
	}
	
	NSError *error = nil;
	if (![[NSFileManager defaultManager] moveItemAtPath:[self path] toPath:newPath error:&error]) {
		// TODO: display the error
	}
}

@dynamic icon;
- (NSImage *)icon {
	if ([self isDirectory])
		return [NSImage imageNamed:@"Folder16x16"];
	return [[NSWorkspace sharedWorkspace] iconForFileType:[[self path] pathExtension]];
}

@dynamic isDirectory;
- (BOOL)isDirectory {
	return _WCFileReferenceFlags.isDirectory;
}

@dynamic directoryPath;
- (NSString *)directoryPath {
	return [[self path] stringByDeletingLastPathComponent];
}

+ (WCFileReference *)fileReferenceWithAlias:(NDAlias *)alias; {
	return [[[[self class] alloc] initWithAlias:alias] autorelease];
}

+ (WCFileReference *)fileReferenceWithFilePath:(NSString *)filePath; {
	return [[[[self class] alloc] initWithFilePath:filePath] autorelease];
}

- (id)initWithFilePath:(NSString *)filePath; {
	return [self initWithAlias:[NDAlias aliasWithPath:filePath]];
}

- (id)initWithAlias:(NDAlias *)alias; {
	if (!(self = [super init]))
		return nil;
	
	_alias = [alias retain];
	
	BOOL isDirectory = NO;
	_WCFileReferenceFlags.isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:[_alias path] isDirectory:&isDirectory] && isDirectory);
	
	return self;
}

- (void)_alertDidEnd:(NSAlert *)alert code:(NSInteger)code info:(void *)info {
	[(id)info autorelease];
	
	if (code != NSAlertDefaultReturn)
		return;
	
	NSString *fileName = [(NSString *)info stringByDeletingPathExtension];
	NSString *fileExtension = [(NSString *)info pathExtension];
	NSString *directoryPath = [self directoryPath];
	NSUInteger fileSuffix = 1;
	while ([[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[[NSString stringWithFormat:@"%@%u", fileName, fileSuffix] stringByAppendingPathExtension:fileExtension]]])
		fileSuffix++;
	
	[self setName:[[NSString stringWithFormat:@"%@%u", fileName, fileSuffix] stringByAppendingPathExtension:fileExtension]];
}
@end
